"use client";

import { useState, useEffect } from "react";
import { Table, Button, Modal, Form, Input, Space, Popconfirm } from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  promptControllerFindAll,
  promptControllerCreate,
  promptControllerUpdate,
  promptControllerRemove,
} from "@/app/servers/api/prompt";

const { TextArea } = Input;

// 使用 API namespace 中定义的类型
type Prompt = API.Prompt;

export default function PromptManagePage() {
  const [prompts, setPrompts] = useState<Prompt[]>([]);
  const [open, setOpen] = useState(false);
  const [editingPrompt, setEditingPrompt] = useState<Prompt | null>(null);
  const [form] = Form.useForm();

  // 获取提示词列表
  const fetchPrompts = async () => {
    try {
      const { data } = await promptControllerFindAll();
      setPrompts(data);
    } catch (error) {
      console.error("Failed to fetch prompts:", error);
    }
  };

  // 创建或更新提示词
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      if (editingPrompt) {
        await promptControllerUpdate(
          { id: editingPrompt.id.toString() },
          values as API.UpdatePromptDto
        );
      } else {
        await promptControllerCreate(values as API.CreatePromptDto);
      }

      setOpen(false);
      setEditingPrompt(null);
      form.resetFields();
      fetchPrompts();
    } catch (error) {
      console.error("Failed to save prompt:", error);
    }
  };

  // 删除提示词
  const handleDelete = async (id: string) => {
    try {
      await promptControllerRemove({ id });
      fetchPrompts();
    } catch (error) {
      console.error("Failed to delete prompt:", error);
    }
  };

  useEffect(() => {
    fetchPrompts();
  }, []);

  const columns: ColumnsType<Prompt> = [
    {
      title: "名称",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "内容",
      dataIndex: "content",
      key: "content",
      ellipsis: true,
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            onClick={() => {
              setEditingPrompt(record);
              form.setFieldsValue(record);
              setOpen(true);
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个提示词吗？"
            onConfirm={() => handleDelete(record.id.toString())}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="p-6">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">提示词管理</h1>
        <Button type="primary" onClick={() => setOpen(true)}>
          新建提示词
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={prompts}
        rowKey="id"
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title={editingPrompt ? "编辑提示词" : "新建提示词"}
        open={open}
        onOk={handleSubmit}
        onCancel={() => {
          setOpen(false);
          setEditingPrompt(null);
          form.resetFields();
        }}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ title: "", content: "" }}
        >
          <Form.Item
            name="title"
            label="名称"
            rules={[{ required: true, message: "请输入提示词名称" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: "请输入提示词内容" }]}
          >
            <TextArea rows={6} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
